<template>
  <div class="merchant-form">
    <cube-form
      :model="model"
      :schema="schema"
      :immediate-validate="false"
      :options="options"
      @validate="validateHandler"
      @submit="submitHandler"
      @reset="resetHandler"></cube-form>
    <loading :show="loading" />
  </div>
</template>

<script>
import Loading from '@/components/Loading'
import api from '@/api'
import base64 from '@/util/base64'
import code from '@/config/code'

// image upload prefix
const UPLOAD = process.env.VUE_APP_BASE_API + '/api/merchant/upload?bucket=merchant/register' +
  '&width=750&height=750&max-width=750&quality=50'

// upload type
const UPLOAD_TYPE = {
  license: 1,
  id: 2,
  shop: 3
}

export default {
  name: 'MerchantForm',
  props: ['status'],
  components: {
    Loading
  },
  data() {
    return {
      loading: false,
      // images list
      idImagesList: [],
      licenseImagesList: [],
      shopImagesList: [],
      // validate
      validity: {},
      valid: undefined,
      // type list
      typeList: [],
      // options
      options: {
        scrollToInvalidField: true,
        layout: 'standard'
      },
      model: {
        name: '',
        nickname: '',
        mobile: '',
        address: '',
        type: '',
        id: [],
        license: [],
        shop: [],
        bank_name: '',
        bank_number: '',
        difference: '20'
      },
      schema: {
        groups: [
          {
            legend: '基本资料',
            fields: [
              {
                type: 'input',
                modelKey: 'name',
                label: '店铺名称',
                props: {
                  placeholder: '请输入名称'
                },
                rules: {
                  required: true
                },
                // validating when blur
                trigger: 'blur'
              },
              {
                type: 'textarea',
                modelKey: 'address',
                label: '地址',
                rules: {
                  required: true
                },
                // debounce validate
                // if set to true, the default debounce time will be 200(ms)
                debounce: 100,
                props: {
                  placeholder: '地址'
                },
              },
              {
                type: 'select',
                modelKey: 'type',
                label: '类型',
                props: {
                  options: []
                },
                rules: {
                  required: true
                }
              },
              {
                type: 'input',
                modelKey: 'nickname',
                label: '申请人姓名',
                props: {
                  placeholder: '真实姓名与银行卡一致'
                },
                rules: {
                  required: true
                },
                // validating when blur
                trigger: 'blur'
              },
              {
                type: 'input',
                modelKey: 'mobile',
                label: '申请人手机',
                props: {
                  placeholder: '手机'
                },
                rules: {
                  required: true
                },
                // validating when blur
                trigger: 'blur'
              },
              {
                type: 'input',
                modelKey: 'bank_name',
                label: '银行',
                props: {
                  placeholder: '如: 中国工商银行'
                },
                rules: {
                  required: true
                },
                // validating when blur
                trigger: 'blur'
              },
              {
                type: 'input',
                modelKey: 'bank_number',
                label: '卡号',
                props: {
                  placeholder: '卡号'
                },
                rules: {
                  required: true
                },
                // validating when blur
                trigger: 'blur'
              },
              {
                type: 'input',
                modelKey: 'difference',
                label: '让利(%)',
                props: {
                  placeholder: '如: 20%'
                },
                rules: {
                  required: true
                },
                // validating when blur
                trigger: 'blur'
              }
            ]
          },
          {
            legend: '上传证件与图片',
            fields: [
              {
                type: 'upload',
                modelKey: 'license',
                label: '营业执照',
                events: {
                  // remove
                  'file-removed': (...args) => {
                    this.removeImage(args[0], 1)
                  },
                  // success (api return data => id)
                  'file-success': (v) => {
                    const { response } = v
                    if (response.code === code.CODE_SUCCESS) {
                      const data = base64.parse(response.data)
                      this.licenseImagesList.push(data)
                    }
                  }
                },
                rules: {
                  required: true,
                  uploaded: (val, config) => {
                    return Promise.all(val.map((file, i) => {
                      return new Promise((resolve, reject) => {
                        return resolve()
                      })
                    })).then(() => {
                      return true
                    })
                  }
                },
                messages: {
                  uploaded: '上传失败'
                },
                props: {
                  // upload api
                  action: {
                    target: UPLOAD + '&type=' + UPLOAD_TYPE.license,
                    fileName: 'file'
                  }
                }
              },
              {
                type: 'upload',
                modelKey: 'id',
                label: '身份证正反面',
                events: {
                  // remove
                  'file-removed': (...args) => {
                    this.removeImage(args[0], 2)
                  },
                  // success (api return data => id)
                  'file-success': (v) => {
                    const { response } = v
                    if (response.code === code.CODE_SUCCESS) {
                      const data = base64.parse(response.data)
                      this.idImagesList.push(data)
                    }
                  }
                },
                rules: {
                  required: true,
                  uploaded: (val, config) => {
                    return Promise.all(val.map((file, i) => {
                      return new Promise((resolve, reject) => {
                        return resolve()
                      })
                    })).then(() => {
                      return true
                    })
                  }
                },
                messages: {
                  uploaded: '上传失败'
                },
                props: {
                  // upload api
                  action: {
                    target: UPLOAD + '&type=' + UPLOAD_TYPE.id,
                    fileName: 'file'
                  }
                }
              },
              {
                type: 'upload',
                modelKey: 'shop',
                label: '实体店图片',
                events: {
                  // remove
                  'file-removed': (...args) => {
                    this.removeImage(args[0], 3)
                  },
                  // success (api return data => id)
                  'file-success': (v) => {
                    const { response } = v
                    if (response.code === code.CODE_SUCCESS) {
                      const data = base64.parse(response.data)
                      this.shopImagesList.push(data)
                    }
                  }
                },
                rules: {
                  required: true,
                  uploaded: (val, config) => {
                    return Promise.all(val.map((file, i) => {
                      return new Promise((resolve, reject) => {
                        return resolve()
                      })
                    })).then(() => {
                      return true
                    })
                  }
                },
                messages: {
                  uploaded: '上传失败'
                },
                props: {
                  // upload api
                  action: {
                    target: UPLOAD + '&type=' + UPLOAD_TYPE.shop,
                    fileName: 'file'
                  }
                }
              }
            ]
          },
          {
            fields: [
              {
                type: 'submit',
                label: '提交',
                props: {
                  primary: true
                }
              }
            ]
          }
        ]
      }
    }
  },
  methods: {
    validateHandler(result) {
      this.validity = result.validity
      this.valid = result.valid
    },
    resetHandler(e) {
    },
    /**
     * type list
     */
    async getType() {
      let { data } = await api.Merchant.typeList()
      data = base64.parse(data)
      if (data.length > 0) {
        data.forEach(x => {
          this.typeList.push({
            text: x.name,
            value: x.id
          })
        })
        // inject form
        this.schema.groups[0].fields[2].props.options = this.typeList
      }
    },
    removeImage(obj, type = 1) {
      // database & new upload image
      let id
      if (obj.id) {
        id = obj.id
      }
      if (obj.response && obj.response.data) {
        id = obj.response.data
        id = base64.parse(id)
      }
      // delete list
      if (type === 1) {
        this.licenseImagesList = this.licenseImagesList.filter(x => x !== id)
      }
      if (type === 2) {
        this.idImagesList = this.idImagesList.filter(x => x !== id)
      }
      if (type === 3) {
        this.shopImagesList = this.shopImagesList.filter(x => x !== id)
      }
    },
    submitHandler(e) {
      e.preventDefault()
      this.loading = true
      api.Merchant.submit({
        ...this.model,
        license_list: this.licenseImagesList,
        id_list: this.idImagesList,
        shop_list: this.shopImagesList
      }).then(response => {
        this.$createToast({
          time: 1000,
          txt: response.message || '操作成功',
          onTimeout: () => {
            this.reload()
            this.$emit('ok')
          }
        }).show()
      }).finally(() => {
        this.loading = false
      })
    },
    fetchData() {
      // submit reject
      if (this.status === 2) {
        this.loading = true
        api.Merchant.edit().then(response => {
          let { data } = response
          data = base64.parse(data)
          // this.model = { ...data }
          this.model.name = data.name
          this.model.address = data.address
          this.model.nickname = data.nickname
          this.model.mobile = data.mobile
          this.model.bank_name = data.bank_name
          this.model.bank_number = data.bank_number
          this.model.type = data.type
          if (Array.isArray(data.images) && data.images.length > 0) {
            data.images.forEach(x => {
              if (+x.type === 1 && x.image && x.image.thumbnail_path) {
                this.model.license.push({
                  id: x.image.id,
                  url: x.image.thumbnail_path
                })
                this.licenseImagesList.push(x.image.id)
              }
              if (+x.type === 2 && x.image && x.image.thumbnail_path) {
                this.model.id.push({
                  id: x.image.id,
                  url: x.image.thumbnail_path
                })
                this.idImagesList.push(x.image.id)
              }
              if (+x.type === 3 && x.image && x.image.thumbnail_path) {
                this.model.shop.push({
                  id: x.image.id,
                  url: x.image.thumbnail_path
                })
                this.shopImagesList.push(x.image.id)
              }
            })
          }
        }).finally(() => {
          this.loading = false
        })
      }
    }
  },
  inject: ['reload'],
  created () {
    this.getType()
    this.fetchData()
  },
  watch: {
    // note: resolve delay status (request api)
    status: {
      handler() {
        if (this.status === 2) {
          this.fetchData()
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="stylus">
.merchant-form
  margin 10px
  background white
</style>
